const record = document.getElementById("record")
const stop = document.getElementById("stop")
const play = document.getElementById("play")
const audio = document.getElementById("audio")
const downWav = document.getElementById("downWav")
const downPcm = document.getElementById("downPcm")
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
canvas.width = 600
canvas.height = 200
let recorder = null

//    获取地址栏参数
let url = window.location.href;
let id = url.split('?')[1].split('=')[1];


// 录制
record.addEventListener("click", () => {
    console.log("录制")
    if(recorder !== null) recorder.close()
    Recorder.get((rec) => {
        recorder = rec
        recorder.start()
    })
})

// 停止
stop.addEventListener("click", () => {
    if(recorder === null) return alert("请先录音")
    recorder.stop()
    // 上传
    const formData = new FormData();
    formData.append('audio', recorder.getBlob());
    formData.append('uuid', id);

    axios.post("/audios", formData).then(res => {
        console.log(res.data);
    }).catch(error => {
        console.log(error);
    });
})

// 播放
// play.addEventListener("click", () => {
//     if(recorder === null) return alert("请先录音")
//     recorder.play(audio, ctx)
//     recorder.draw(ctx)
// })
//拿到数据库的音频数据，进行播放
play.addEventListener("click", () => {
    console.log("播放")
    axios.get("/audios/"+id).then(res => {
        let audioData = res.data.data.audio;
        let binaryString = atob(audioData);
        let len = binaryString.length;
        let bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        // 创建一个 Blob 对象
        let blob = new Blob([bytes.buffer], {type: 'audio/ogg; codecs=opus'});
        // 创建一个 Object URL
        audio.src = window.URL.createObjectURL(blob);
        audio.play(audio, ctx);
        // dr(ctx);
    }).catch(error => {
        console.log(error);
    });
})

// 下载 wav
downWav.addEventListener("click", () => {
    if(recorder === null) return alert("请先录音")
    const src = recorder.wavSrc()
    downWav.setAttribute("href", src)
})

// 下载 pcm
downPcm.addEventListener("click", () => {
    if(recorder === null) return alert("请先录音")
    const src = recorder.pcmSrc()
    downPcm.setAttribute("href", src)
})

/*暂停、继续功能*/
const pause = document.getElementById("pause");  // 暂停、继续按钮
let isPaused = false;  // 初始状态：正在录音
pause.addEventListener("click", () => {
    if(recorder === null) return alert("请先录音")
    if(isPaused) {
        recorder.resume();
        pause.innerText = "暂停";
    } else {
        recorder.pause();
        pause.innerText = "继续";
    }
    isPaused = !isPaused;
})

/*重新录制*/
const reset = document.getElementById("reset");
reset.addEventListener("click", () => {
    recorder.restart();
    pause.innerText = "暂停";
    isPaused = false;
})